
package cn.edu.scau.cmi.front.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;

import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.domain.Adultertype;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Foodbatch;
import cn.edu.scau.cmi.ema.domain.Foodtype;
import cn.edu.scau.cmi.ema.domain.Picture;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.util.CmiEntityUtil;
import cn.edu.scau.cmi.front.dao.CmiEventDAO;
import cn.edu.scau.cmi.front.dao.CmiPictureDAO;
import cn.edu.scau.cmi.front.domain.FrontEventPagination;
import cn.edu.scau.cmi.front.service.CmiFoodTypeIdService;

/**
 * 没什么用的方法，待确认后逐步删除
 * 
 */

@Controller("FrontMenuController")



public class FrontMenuController extends FrontCmiEmaController {
	
//	CmiPagination cmiPagination = new CmiPagination();
	


	//	原来的默认首页，现在用于用户登录后的首页
	@RequestMapping("/frontPublic")
	public ModelAndView forntPublic() {
		ModelAndView mav = new ModelAndView();
//		公众页面显示5个图片，当前只有9个图片。
		Set<Picture> pictures = pictureDAO.findAllPictures(-1, 9);
		mav.addObject("pictures",pictures);
		mav.setViewName("front/frontPublic.jsp");
		return mav;
	}
	
	
//	乐老师的毒理库
	@RequestMapping("/frontToxic")
	public ModelAndView frontToxic() {
		ModelAndView mav = new ModelAndView();
//		公众页面显示5个图片，当前只有9个图片。
		Set<Picture> pictures = pictureDAO.findAllPictures(-1, 5);
		mav.addObject("pictures",pictures);
		mav.setViewName("front/frontToxic.jsp");
		return mav;
	}
	
//	原来的默认首页，现在用于用户登录后的首页
	@RequestMapping("/frontMenu")
	public ModelAndView forntMenu() {
		ModelAndView mav = new ModelAndView();
		// cmiPictureDAO.updatePicture();
		Set<Picture> pictures = null;

		pictures = frontService.getExhibinatePictures(1, cmiFoodTypeIdService.getAgriculturalProductIdSet());
		if (pictures.size() > 0)
			mav.addObject("agriculturalProductPicture", ((Picture) pictures.toArray()[0]).getPath());
		else
			mav.addObject("agriculturalProductPicture", "");

		pictures = frontService.getExhibinatePictures(1, cmiFoodTypeIdService.getMeatIdSet());
		if (pictures.size() > 0)
			mav.addObject("meatPicture", ((Picture) pictures.toArray()[0]).getPath());
		else
			mav.addObject("meatPicture", "");

		pictures = frontService.getExhibinatePictures(1, cmiFoodTypeIdService.getAquaticIdSet());
		if (pictures.size() > 0)
			mav.addObject("aquaticPicture", ((Picture) pictures.toArray()[0]).getPath());
		else
			mav.addObject("aquaticPicture", "");

		pictures = frontService.getExhibinatePictures(1, cmiFoodTypeIdService.getMilkIdSet());
		if (pictures.size() > 0)
			mav.addObject("milkPicture", ((Picture) pictures.toArray()[0]).getPath());
		else
			mav.addObject("milkPicture", "");

		pictures = frontService.getExhibinatePictures(1, cmiFoodTypeIdService.getGrainAndOilIdSet());
		if (pictures.size() > 0)
			mav.addObject("grainAndOilPicture", ((Picture) pictures.toArray()[0]).getPath());
		else
			mav.addObject("grainAndOilPicture", "");

		pictures = frontService.getExhibinatePictures(1, cmiFoodTypeIdService.getOtherIdSet());
		if (pictures.size() > 0)
			mav.addObject("otherPicture", ((Picture) pictures.toArray()[0]).getPath());
		else
			mav.addObject("otherPicture", "");

		mav.setViewName("front/frontMenu.jsp");
		return mav;
	}

	@RequestMapping("/frontReport")
	public ModelAndView frontReport() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontReport.jsp");
		return mav;
	}
	
	/**
	 * Show the latest three Event entities to frontPage
	 * 
	 */
	@RequestMapping("/frontIndex")
	public ModelAndView frontIndex(HttpServletRequest request) {

		Integer foodtypeId = Integer.valueOf(request.getParameter("foodtypeId"));

		ModelAndView mav = new ModelAndView();
//		List<Calendar> dates = new LinkedList<Calendar>();
//		Set<Picture> pictures = new LinkedHashSet<Picture>();// 用于首页跑马灯效果，是最新的事件中的最新的记录的图片
//
//		pictures = frontService.getNewestEventsReprestativePictures(10);// 暂时定5个最新事件的有代表性的图片

		Set<Integer> foodtypeIdSet = cmiFoodTypeIdService.getFoodtypeIdSetByFoodtypeId(foodtypeId);
		String foodtypeName = cmiFoodTypeIdService.getFoodtypeNameByFoodtypeId(foodtypeId);

		Set<String> basicAttributes = CmiEntityUtil.getAllBasicFieldNames(Event.class);
//		获取最新的5张图片，在页面跑马灯展示
		Set<Picture> pictures = frontService.getExhibinatePictures(5, foodtypeIdSet);

		mav.addObject("pictures", pictures);
//		mav.addObject("dates", dates);
		mav.addObject("foodtypeName", foodtypeName);
		mav.addObject("basicAttributes", basicAttributes);
		mav.addObject("basicAttributesSize", basicAttributes.size());
		FrontEventPagination cmiPagination = new FrontEventPagination();
		mav.addObject("page", cmiPagination);

		mav.setViewName("front/frontIndex.jsp");
		return mav;
	}
	


	/**
	 * Show one Event entity to frontPage
	 * 
	 */
	@RequestMapping("/frontDetailEvent")
	public ModelAndView frontDetailEvent(@RequestParam Integer id, @RequestParam(required = false) Integer foodtypeId) {
		ModelAndView mav = new ModelAndView();

		Event event = eventService.findEventByPrimaryKey(id);
		Set<Event> childEvents = event.getEventsForParent();// 遍历事件的子事件
		Event theEarliestEvent = null;

		if (foodtypeId == null) {
			foodtypeId = event.getFoodbatch().getFood().getFoodtype().getId();
		}
		// 用于前端列表事件功能
//		cmiPagination.setFoodtypeId(foodtypeId);

//		事件的第一条记录，找到discoverytime最早的事件，逻辑上不一定对，暂时这样处理。QUESTION----->>唐锦文
		Iterator<Event> childEventIterator = childEvents.iterator();
		if (childEventIterator.hasNext()) {
			theEarliestEvent = childEventIterator.next();
			for (Event r : childEvents) {
				if (r.getDiscoveryTime() != null && theEarliestEvent.getDiscoveryTime() != null) {
					if (r.getDiscoveryTime().compareTo(theEarliestEvent.getDiscoveryTime()) < 0) {
						theEarliestEvent = r;
					}
				}

			}
		}

		// 此处逻辑有问题，要确定需求之后才能改。QUESTION----->>唐锦文
		Calendar date = (theEarliestEvent == null ? Calendar.getInstance() : theEarliestEvent.getDiscoveryTime());
		// Calendar date = theEarliestEvent.getDiscoveryTime();
		Set<Picture> pictures = event.getPicturesForEvent();
//		Picture picture = null;
//		取得事件的第一张图片，第一张图片不一定具有某种意义，如最新图片，最旧图片等等。----->>唐锦文

//		if (!pictures.isEmpty()) {
//			picture = pictures.iterator().next();
//		}

//		int found = 0;
//		for (Event r : events) {
//			if (found == 1) {
//				break;
//			} else if (r.getPicturesForEvent().size() != 0) {
//				Set<Event> newEvents = r.getEventsForParent();// 遍历事件的子事件Set集合的子事件
//				for (Event rd : newEvents) {
//					if (rd.getPicturesForEvent().size() != 0) {
//						Set<Picture> pictures = rd.getPicturesForEvent();
//						picture = pictures.iterator().next();
//						found = 1;
//						break;
//					}
//				}
//			}
//		}

		// 根据当前事件的食品类型，获取最新的5个事件
		// TODO 有一个奇怪的bug，如果把下面那段放在替换description的下面，替换的description会更新到数据库
//		事件的相关事件，用于在界面的下部分显示，因为frontListEvent.jsp页面使用的是events名称，因此，这个名称也采用
//		ByFoodtypeIdAndEventStatusExcludeEventIdDesc
		List<Event> foodRelativeEvents = cmiEventDAO.findFoodRelativEvents(event.getId(), 0, 10);
		List<Event> foodtypeRelativeEvents = cmiEventDAO.findFoodtypeRelativEvents(event.getId(), 0, 10);
		List<Event> discoveryaddressRelativeEvents = cmiEventDAO.findDiscoveryadddressRelativEvents(event.getId(), 0, 10);
		List<Event> sourceaddressRelativeEvents = cmiEventDAO.findSourceAddressRelativEvents(event.getId(), 0, 10);

		
//		获取事件的关联事件
		Map<Event, Picture> foodRelativEventPictureMap = frontService.getRepresentativePictureOfEvents(new LinkedHashSet<Event>(foodRelativeEvents));
		Map<Event, Picture> foodtypeRelativEventPictureMap = frontService.getRepresentativePictureOfEvents(new LinkedHashSet<Event>(foodtypeRelativeEvents));
		Map<Event, Picture> discoveryaddressRelativEventPictureMap = frontService.getRepresentativePictureOfEvents(new LinkedHashSet<Event>(discoveryaddressRelativeEvents));
		Map<Event, Picture> sourcaddressRelativEventPictureMap = frontService.getRepresentativePictureOfEvents(new LinkedHashSet<Event>(sourceaddressRelativeEvents));

		
//		把event中的description内容中的回车换行键替换为段落标记
		String description = event.getDescription();
		if (description != null) {
			description = description.replaceAll("\\r\\n", "</p><p>");
			description = description.replaceAll("\\n", "</p><p>");
			description = "<p>" + description;
			description = description + "</p>";
			event.setDescription(description);
		}

//		报道事件的网站间接关系：event->uri->site

//		Set<Uri> uris = new HashSet<Uri>();
//		// 实际事件是否一定具有uri？否的话要加判断。----->>唐锦文
//		if (event.getUri() != null) {
//			uris.add(event.getUri());
//		}
//		/**
//		 * 子事件的site也一起加进来
//		 */
//		for(Event ev:event.getEventsForParent()) {
//			if(ev.getUri()!=null) {
//				uris.add(ev.getUri());
//			}
//		}

		// 筛选出快照
		Picture snapshot = null;
		for (Picture picture : pictures) {
			if (picture.getPath().startsWith("snapshot_"))
				snapshot = picture;
		}

		mav.addObject("foodtypeName", cmiFoodTypeIdService.getFoodtypeNameByFoodtypeId(foodtypeId));
		FrontEventPagination cmiPagination =  new FrontEventPagination();
		
		mav.addObject("foodtypeId", foodtypeId );
		// 用于前端列表事件功能
		
		
		mav.addObject("page", cmiPagination );
//		mav.addObject("uris", uris);
		mav.addObject("event", event);
		
		mav.addObject("date", date);
		mav.addObject("pictures", pictures);
		mav.addObject("snapshot", snapshot);
		
		mav.addObject("foodRelativeEvents", foodRelativeEvents);
		mav.addObject("foodtypeRelativeEvents", foodtypeRelativeEvents);
		mav.addObject("sourceaddressRelativeEvents", sourceaddressRelativeEvents);
		mav.addObject("discoveryaddressRelativeEvents", discoveryaddressRelativeEvents);
		
		mav.addObject("foodRelativEventPictureMap", foodRelativEventPictureMap);
		mav.addObject("foodtypeRelativEventPictureMap", foodtypeRelativEventPictureMap);
		mav.addObject("discoveryaddressRelativEventPictureMap", discoveryaddressRelativEventPictureMap);
		mav.addObject("sourcaddressRelativEventPictureMap", sourcaddressRelativEventPictureMap);
		
		mav.setViewName("front/frontDetailEvent.jsp");
		return mav;
	}



	/**
	 * Show the map 事件，时间，食品
	 * 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/frontMap")
	public ModelAndView frontMap(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String eventsSelected = request.getParameter("events");
		String subjectsSelected = request.getParameter("subjects");
		String sourceAddress = request.getParameter("SourceAddress");
		String discoveryAddress = request.getParameter("DiscoveryAddress");
		String foodtypeLibraryStr = request.getParameter("foodtypeLibrary");
		Set<Integer> foodtypeLibrarySet = null;
		if (foodtypeLibraryStr != null) {
			Integer foodtypeLibrary = Integer.valueOf(foodtypeLibraryStr);
			foodtypeLibrarySet = cmiFoodTypeIdService.getFoodtypeIdSetByFoodtypeId(foodtypeLibrary);
		}
		//TODO 2020年10月7号：561是粮食加工品的id，前面考虑的是分类别库，现在不考虑了，所有的加工食品和
//		Integer foodtypeId = Integer.valueOf(request.getParameter("foodtypeId"));
		Set<Integer> foodtypeIdSet = cmiFoodTypeIdService.getFoodtypeIdSetByFoodtypeId(561);

		Set<Event> events = new HashSet<Event>();

		if (eventsSelected != null && !eventsSelected.trim().equals("")) {
			String[] eventSplit = eventsSelected.split(",");
			HashSet<Integer> subjectSet = new HashSet<Integer>();
			if (subjectsSelected != null && !subjectsSelected.trim().equals("")) {
				String[] subjectSplit = subjectsSelected.split(",");
				for (String str : subjectSplit) {
					subjectSet.add(Integer.valueOf(str));
				}
			}
			for (String string : eventSplit) {
				int eventKey = Integer.valueOf(string);
				Event event = eventService.findEventByPrimaryKey(eventKey);
				if (subjectSet.size() > 0 && subjectSet.contains(event.getSubject().getId())
						|| subjectSet.size() <= 0) {
					events.add(event);
				}
			}
		} else if (subjectsSelected != null && !subjectsSelected.trim().equals("")) {
			String[] split = subjectsSelected.split(",");
			for (String string : split) {
				int subjectKey = Integer.valueOf(string);
				// events.addAll(eventDAO.findEventsBySubject(subjectKey, -1, -1));
				Set<Event> eventsBySubject = eventDAO.findEventsBySubject(subjectKey, -1, -1);
				for (Event e : eventsBySubject) {
					if (foodtypeIdSet.contains(e.getFoodbatch().getFood().getFoodtype().getId())) {
						events.add(e);
					}
				}
			}
		} else if (foodtypeLibrarySet != null) {
			// 获取子库的事件
			events.addAll(cmiEventDAO.findEventsByFoodtypeId(foodtypeLibrarySet, -1, -1));
		} else {
			events.addAll(cmiEventDAO.findEventsByFoodtypeId(foodtypeIdSet, 0, 10));
		}

		JSONArray jsonArray = new JSONArray();
		for (Event event : events) {
			if (sourceAddress != null && event.getSourceAddress() != null && event.getSourceAddress().getName() != null
					&& !event.getSourceAddress().getName().equals("无") && !jsonArray.contains(event.getSourceAddress().getName()))
				jsonArray.add(event.getSourceAddress().getName());
			if (discoveryAddress != null && event.getDiscoveryAddress() != null && event.getDiscoveryAddress().getName() != null
					&& !event.getDiscoveryAddress().getName().equals("无") && !jsonArray.contains(event.getDiscoveryAddress().getName()))
				jsonArray.add(event.getDiscoveryAddress().getName());
		}
		mav.addObject("addresssJsonString", jsonArray);
//		mav.addObject("foodtypeName", cmiFoodTypeIdService.getFoodtypeNameByFoodtypeId(foodtypeId));
		mav.addObject("foodtypeName", "事件区域分布");
		mav.setViewName("front/frontMap.jsp");
		return mav;
	}

	/**
	 * add a event
	 * 
	 */
	@RequestMapping("/frontUploadEvent")
	public ModelAndView frontUploadEvent(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontUploadEvent.jsp");
		return mav;
	}

	@RequestMapping("/frontReporting")
	public ModelAndView frontReporting() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontReporting.jsp");
		return mav;
	}

	@RequestMapping(value = "/getAddress", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getAdress(@RequestParam(value = "Id") String Id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Set<Integer> setId = new HashSet<Integer>();
		List<String> list = new ArrayList<String>();
		setId = addressDAO.findAddressIdsByParent(Integer.valueOf(Id));
		for (Integer i : setId) {
			list.add(addressDAO.findAddressById(i).getName());
		}
		map.put("setId", setId);
		map.put("list", list);
		return map;
	}
	
}